package com.pinyougou.sellergoods.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pinyougou.mapper.TbSpecificationOptionMapper;
import com.pinyougou.mapper.TbTypeTemplateMapper;
import com.pinyougou.pojo.TbSpecificationOption;
import com.pinyougou.pojo.TbSpecificationOptionExample;
import com.pinyougou.pojo.TbTypeTemplate;
import com.pinyougou.pojo.TbTypeTemplateExample;
import com.pinyougou.sellergoods.service.TypeTemplateService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

@Service
public class TypeTemplateServiceImpl implements TypeTemplateService {

    @Autowired
    private TbTypeTemplateMapper typeTemplateMapper;

    @Autowired
    private TbSpecificationOptionMapper specificationOptionMapper;

    @Override
    public PageInfo<TbTypeTemplate> findAll(TbTypeTemplate tbTypeTemplate, Integer page, Integer size) {
        PageHelper.startPage(page,size);
        TbTypeTemplateExample example = new TbTypeTemplateExample();
        if (tbTypeTemplate != null) {
            //名字模糊搜索
            if (tbTypeTemplate.getName() != null && tbTypeTemplate.getName().length() > 0 && tbTypeTemplate.getName().trim().length() > 0) {
                example.createCriteria().andNameLike(tbTypeTemplate.getName());
            }
        }
        List<TbTypeTemplate> tbTypeTemplates = typeTemplateMapper.selectByExample(example);
        return new PageInfo<>(tbTypeTemplates);
    }

    @Override
    public TbTypeTemplate getOneById(long id) {
        TbTypeTemplate tbTypeTemplate = typeTemplateMapper.selectByPrimaryKey(id);
        return tbTypeTemplate;
    }

    @Override
    public List<Map> getOptionTypeId(long id) {
        TbTypeTemplate tbTypeTemplate = typeTemplateMapper.selectByPrimaryKey(id);
        TbSpecificationOptionExample example = new TbSpecificationOptionExample();
        String specIds = tbTypeTemplate.getSpecIds();

        List<Map> maps = JSON.parseArray(specIds, Map.class);

        for (Map map : maps) {
            long specId = Long.parseLong(map.get("id").toString());
            example.createCriteria().andSpecIdEqualTo(specId);
            List<TbSpecificationOption> options = specificationOptionMapper.selectByExample(example);
            map.put("options",options);
        }

        return maps;
    }
}
